package com.android.happymall.activity.mine;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.happymall.R;
import com.android.happymall.model.member.DataEditAvatar;
import com.android.happymall.model.member.DataEditAvatarCallback;
import com.android.happymall.utils.ConstantsUrl;
import com.android.happymall.utils.MyLog;
import com.android.happymall.utils.ObjectUtils;
import com.android.happymall.view.dialog.MainMsg;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.android.happymall.R.id.ll_change_sex;

public class DataEditActivity extends TakePhotoActivity {
    @BindView(R.id.ll_change_avatar_img)
    ImageView llChangeAvatarImg;
    @BindView(R.id.ll_change_name_tv)
    TextView llChangeNameTv;
    @BindView(R.id.ll_change_sex_tv)
    TextView ll_change_sex_tv;
    @BindView(R.id.ll_change_phone_tv)
    TextView llChangePhoneTv;

    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;
    @BindView(R.id.main_top_title)
    TextView mainTopTitle;
    @BindView(R.id.main_top_back)
    ImageView mainTopBack;
    private TakePhoto takePhoto;
    private DataEditActivity mcontext;
    private MainMsg mdialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_edit);
        ButterKnife.bind(this);
        mcontext = DataEditActivity.this;
        ObjectUtils.StatusBarWhiteBg(mcontext, false);
        mainTopTitle.setText("个人资料");
        mainTopBack.setVisibility(View.VISIBLE);
        String member_avatar = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_MEMBER_DATAEDIT_AVATAR);
        String member_nick = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_MEMBER_DATAEDIT_NICK);
        String member_phone = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_MEMBER_DATAEDIT_PHONE);
        String sexy = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_MEMBER_DATAEDIT_SEXY);
        ObjectUtils.photoCircle(mcontext, member_avatar, llChangeAvatarImg);
        llChangeNameTv.setText(member_nick);
        llChangePhoneTv.setText(member_phone);
        if(sexy.equals("1"))
        {
            ll_change_sex_tv.setText("男");
        }
        else
        {
            ll_change_sex_tv.setText("女");
        }
        initUI();
    }

    /**
     * 编辑
     */
    private ArrayList<String> mList = new ArrayList<>();

    private void initUI() {
        //初始化
        takePhoto = getTakePhoto();

        mdialog = new MainMsg(mcontext);
        mdialog.setOnSetCameraClickListener(new MainMsg.OnTaktPhotoClickListener() {
            @Override
            public void onClickCamera() {
                Uri uri = configCompress();
                takePhoto.onPickFromCapture(uri);
                mdialog.close();
            }

            @Override
            public void onClickGallery() {
                configCompress();
                int size = mList.size();
                takePhoto.onPickMultiple(1 - size);
                mdialog.close();
            }
        });

    }

    //压缩
    private Uri configCompress() {
        File file = new File(Environment.getExternalStorageDirectory(), "/aishangauctioning/" + System.currentTimeMillis() + ".png");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        Uri imageUri = Uri.fromFile(file);
        CompressConfig config = new CompressConfig.Builder().setMaxSize(100 * 1024).setMaxPixel(1000).create();
        takePhoto.onEnableCompress(config, true);
        return imageUri;
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        ArrayList<TImage> images = result.getImages();
        mList.clear();
        mList.add(images.get(0).getCompressPath());
        GetDataUpdate();
    }

    private void GetDataUpdate() {
        if (mList.size() > 0) {
            boolean networkConnected = ObjectUtils.isNetworkConnected(mcontext);
            String address = ConstantsUrl.domain + ConstantsUrl.MEMBERDATA_EDITAVATAR;
            MyLog.e("主页列表", "主页列表" + address);
            if (networkConnected) {
                progressLoading.setVisibility(View.VISIBLE);
                HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
                HashMap<String, String> map = new HashMap<>();
                PostFormBuilder post = OkHttpUtils.post();
                File file = new File(mList.get(0));
                post.addFile("file", String.valueOf(System.currentTimeMillis()) + ".png", file);
                post.url(address)
                        .headers(header)
                        .params(map)
                        .build()
                        .execute(new DataEditAvatarCallback() {

                            @Override
                            public void onError(Call call, Exception e, int id) {
                                progressLoading.setVisibility(View.GONE);
                                MyLog.e("连接错误", "" + e.toString());

                            }

                            @Override
                            public void onResponse(DataEditAvatar response, int id) {
                                progressLoading.setVisibility(View.GONE);
                                ObjectUtils.toast(mcontext, response.getMsg());
                                if (response.getCode() == 0) {

                                    ObjectUtils.photoCircle(mcontext, response.getAvatar(), llChangeAvatarImg);
                                } else {
                                    if(response.getCode() == 40001){
                                        ObjectUtils.reLogin(mcontext);
                                    }
                                    return;
                                }

                            }

                        });
            } else {
                ObjectUtils.toast(mcontext, "网络未连接");
            }
        }
    }

    private static final int TO_REPLY_N = 1;
    private static final int TO_REPLY_M = 2;
    private static final int TO_REPLY_P = 3;
    private static final int TO_REPLY_S = 4;
    @OnClick({R.id.ll_change_avatar, R.id.ll_change_name, R.id.ll_change_phone, R.id.ll_change_pd, ll_change_sex, R.id.main_top_back})
    public void onClick(View view) {
        Intent share = new Intent(mcontext, TransparentActivity.class);
        switch (view.getId()) {
            case ll_change_sex:
                share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_TYPE, 6);
                startActivityForResult(share, TO_REPLY_S);
                break;
            case R.id.ll_change_avatar:
                mdialog.show(mcontext.getWindow().getDecorView(), 1, null);
                break;
            case R.id.ll_change_name:
                String member_nick = llChangeNameTv.getText().toString().trim();
                share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_TYPE, 3);
                share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_MEMBER_DATA, member_nick);
                startActivityForResult(share, TO_REPLY_N);
                break;
            case R.id.ll_change_phone:
                share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_TYPE, 4);
                startActivityForResult(share, TO_REPLY_M);
                break;
            case R.id.ll_change_pd:
                share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_TYPE, 5);
                startActivityForResult(share, TO_REPLY_P);
                break;
            case R.id.main_top_back:
                finish();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == TO_REPLY_N) {
            String data_result = data.getStringExtra("data_result");
            llChangeNameTv.setText(data_result);
            return;
        }
        if (requestCode == TO_REPLY_S) {
            String data_result = data.getStringExtra("data_result");
            ll_change_sex_tv.setText(data_result);
            return;
        }
        if (requestCode == TO_REPLY_M) {
            String data_result = data.getStringExtra("data_result");
            llChangePhoneTv.setText(data_result);
            return;
        }
        if (requestCode == TO_REPLY_P) {
            return;
        }

    }

}
